package com.example.petadopt.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.petadopt.R;
import com.example.petadopt.common.Result;
import com.example.petadopt.dao.PetDao;
import com.example.petadopt.entity.Pet;
import com.gzone.university.utils.AlbumUtils;
import com.gzone.university.utils.GlideUtils;

import java.util.ArrayList;
import java.util.List;

public class PetEditActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_PICK_IMAGE = 1001;

    private ImageButton btnBack;
    private TextView tvTitle;
    private Button btnSave;
    private ImageView ivPetPhoto;
    private Button btnUploadPhoto;
    private EditText etName;
    private EditText etBreed;
    private EditText etAge;
    private Spinner spinnerGender;
    private EditText etWeight;
    private CheckBox cbVaccinated;
    private CheckBox cbSterilized;
    private CheckBox cbDewormed;
    private CheckBox cbRabiddog;

    private Long petId;
    private Pet currentPet;
    private String selectedImagePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pet_edit);

        // 初始化视图
        initView();
        // 初始化监听器
        initListener();
        // 初始化数据
        initData();
    }

    private void initView() {
        btnBack = findViewById(R.id.btn_back);
        tvTitle = findViewById(R.id.tv_title);
        btnSave = findViewById(R.id.btn_save);
        ivPetPhoto = findViewById(R.id.iv_pet_photo);
        btnUploadPhoto = findViewById(R.id.btn_upload_photo);
        etName = findViewById(R.id.et_name);
        etBreed = findViewById(R.id.et_breed);
        etAge = findViewById(R.id.et_age);
        spinnerGender = findViewById(R.id.spinner_gender);
        etWeight = findViewById(R.id.et_weight);
        cbVaccinated = findViewById(R.id.cb_vaccinated);
        cbSterilized = findViewById(R.id.cb_sterilized);
        cbDewormed = findViewById(R.id.cb_dewormed);
        cbRabiddog = findViewById(R.id.cb_rabiddog);

        String[] genders = {"公猫", "母猫", "公狗", "母狗"};
        ArrayAdapter<String> genderAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, genders);
        spinnerGender.setAdapter(genderAdapter);
    }

    private void initListener() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePet();
            }
        });

        btnUploadPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });
    }

    private void initData() {
        // 获取传递的宠物ID
        petId = getIntent().getLongExtra("pet_id", -1);
        if (petId > 0) {
            // 编辑模式
            tvTitle.setText("编辑宠物");
            loadPetData(petId);
        } else {
            // 添加模式
            tvTitle.setText("添加宠物");
            currentPet = new Pet();
        }
    }

    private void loadPetData(Long petId) {
        Result<Pet> result = PetDao.getPetById(petId);
        if (result.isSuccess() && result.getData() != null) {
            currentPet = result.getData();

            // 填充表单数据
            etName.setText(currentPet.getName());

            etBreed.setText(currentPet.getBreed());
            etAge.setText(String.valueOf(currentPet.getAge()));

            // 设置性别
            String gender = currentPet.getGender();
            if (gender.contains("公猫")) {
                spinnerGender.setSelection(0);
            } else if (gender.contains("母猫")) {
                spinnerGender.setSelection(1);
            } else if (gender.contains("公狗")) {
                spinnerGender.setSelection(2);
            } else if (gender.contains("母狗")) {
                spinnerGender.setSelection(3);
            } else {
                spinnerGender.setSelection(0);
            }

            if (currentPet.getWeight() != null) {
                etWeight.setText(String.valueOf(currentPet.getWeight()));
            }

            // 设置健康状况
            List<String> healthStatus = currentPet.getHealthStatus();
            if (healthStatus != null) {
                for (String status : healthStatus) {
                    if (status.contains("已注射三联疫苗")) {
                        cbVaccinated.setChecked(true);
                    }
                    if (status.contains("已绝育")) {
                        cbSterilized.setChecked(true);
                    }
                    if (status.contains("已完成体内外驱虫")) {
                        cbDewormed.setChecked(true);
                    }
                    if (status.contains("已接种狂犬疫苗")) {
                        cbRabiddog.setChecked(true);
                    }
                }
            }

            // 设置图片
            if (currentPet.getImage() != null && !currentPet.getImage().isEmpty()) {
                selectedImagePath = currentPet.getImage();
                GlideUtils.load(ivPetPhoto, selectedImagePath);
            }
        } else {
            Toast.makeText(this, "加载宠物信息失败", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void savePet() {
        // 验证表单
        String name = etName.getText().toString().trim();
        if (name.isEmpty()) {
            Toast.makeText(this, "请输入宠物名称", Toast.LENGTH_SHORT).show();
            return;
        }

        String breed = etBreed.getText().toString().trim();
        if (breed.isEmpty()) {
            Toast.makeText(this, "请输入宠物品种", Toast.LENGTH_SHORT).show();
            return;
        }

        String ageStr = etAge.getText().toString().trim();
        if (ageStr.isEmpty()) {
            Toast.makeText(this, "请输入宠物年龄", Toast.LENGTH_SHORT).show();
            return;
        }
        if (selectedImagePath == null) {
            Toast.makeText(this, "请上传宠物照片", Toast.LENGTH_SHORT).show();
            return;
        }

        // 构建宠物对象
        if (currentPet == null) {
            currentPet = new Pet();
        }
        currentPet.setName(name);
        currentPet.setBreed(breed);
        currentPet.setAge(Integer.parseInt(ageStr));

        // 设置性别
        String gender = spinnerGender.getSelectedItem().toString();
        currentPet.setGender(gender);

        // 设置体重
        String weightStr = etWeight.getText().toString().trim();
        if (!weightStr.isEmpty()) {
            currentPet.setWeight(Double.parseDouble(weightStr));
        }

        // 设置健康状况
        List<String> healthStatus = new ArrayList<>();
        if (cbVaccinated.isChecked()) {
            healthStatus.add("已注射三联疫苗");
        }
        if (cbDewormed.isChecked()) {
            healthStatus.add("已完成体内外驱虫");
        }
        if (cbRabiddog.isChecked()) {
            healthStatus.add("已接种狂犬疫苗");
        }
        if (cbSterilized.isChecked()) {
            healthStatus.add("已绝育");
        }
        currentPet.setHealthStatus(healthStatus);

        // 设置图片路径
        currentPet.setImage(selectedImagePath);

        // 保存宠物信息
        Result<Void> result;
        if (petId > 0) {
            // 更新宠物
            result = PetDao.updatePet(currentPet);
        } else {
            // 添加宠物
            result = PetDao.addPet(currentPet);
        }

        if (result.isSuccess()) {
            Toast.makeText(this, petId > 0 ? "更新宠物信息成功" : "添加宠物成功", Toast.LENGTH_SHORT).show();
            // 返回上一页
            finish();
        } else {
            Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void openGallery() {
        AlbumUtils.openAlbum(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AlbumUtils.OPEN_ALBUM_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            selectedImagePath = AlbumUtils.getImagePath(data);
            GlideUtils.load(ivPetPhoto, selectedImagePath);
        }
    }
} 